package com.pactera.madp.cp.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pactera.madp.admin.api.constant.CrmDictTypeConstants;
import com.pactera.madp.admin.api.entity.SysDictItem;
import com.pactera.madp.cp.api.feign.RemoteDictService;
import com.pactera.madp.cp.api.constant.CrmFieldNameConstants;
import com.pactera.madp.cp.api.dto.contactfieldpivot.ContactFieldPivotDto;
import com.pactera.madp.cp.api.dto.crm.CrmCustomQueryConditionDTO;
import com.pactera.madp.cp.api.dto.workcontacttag.WorkContactTagDTO;
import com.pactera.madp.cp.api.em.medium.TypeEnum;
import com.pactera.madp.cp.api.em.workcontact.EventEnum;
import com.pactera.madp.cp.api.entity.*;
import com.pactera.madp.cp.api.entity.crm.WorkCustomInfoEntity;
import com.pactera.madp.cp.api.vo.ContactFieldPivotVO;
import com.pactera.madp.cp.common.util.WxApiUtils;
import com.pactera.madp.cp.common.util.ali.AliyunOssUtils;
import com.pactera.madp.cp.handler.CorpContextHolder;
import com.pactera.madp.cp.mapper.ContactFieldPivotMapper;
import com.pactera.madp.cp.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author zhaojinjian
 * @ClassName WorkContactFieldPivotServiceImpl.java
 * @Description TODO
 * @createTime 2020/12/24 16:47
 */
@Service
@Slf4j
public class WorkContactFieldPivotServiceImpl extends ServiceImpl<ContactFieldPivotMapper, ContactFieldPivotEntity> implements IWorkContactFieldPivotService {

    @Autowired
    private IContactFieldService contactFieldService;
    @Autowired
    @Lazy
    private IContactService contactService;
    @Autowired
    ContactFieldTypeService contactFieldTypeService;
    @Autowired
    private IWorkContactTagService contactTagService;
    @Autowired
    private IWorkContactEmployeeService workContactEmployeeService;
    @Autowired
    private WorkCustomInfoService workCustomInfoService;
    @Autowired
    private RemoteDictService remoteDictService;

    /**
     * @description 客户 - 客户详情 - 用户画像
     * @author zhaojinjian
     * @createTime 2020/12/24 18:02
     */
    @Override
    public List<ContactFieldPivotVO> getContactFieldPivotList(Integer contactId) {
        List<ContactFieldPivotVO> voList = new ArrayList<>();

        List<ContactFieldEntity> contactFieldEntityList = contactFieldService.list(Wrappers.<ContactFieldEntity>lambdaQuery()
                .eq(ContactFieldEntity::getCorpId, CorpContextHolder.getCorpId())
                .eq(ContactFieldEntity::getStatus,1));
        contactFieldEntityList.sort(Comparator.comparing(ContactFieldEntity::getOrder,Comparator.reverseOrder()).thenComparing(BaseEntity::getCreateTime,Comparator.reverseOrder()));
        QueryWrapper<ContactFieldPivotEntity> contactFieldPivotWrapper = new QueryWrapper<>();
        contactFieldPivotWrapper.eq("contact_id", contactId);
        List<ContactFieldPivotEntity> contactFieldPivotEntityList = this.list(contactFieldPivotWrapper);
        HashMap<Integer, ContactFieldPivotEntity> contactFieldPivotEntityMap = new HashMap<>(contactFieldPivotEntityList.size());
        for (ContactFieldPivotEntity e : contactFieldPivotEntityList) {
            contactFieldPivotEntityMap.put(e.getContactFieldId(), e);
        }

        ContactFieldPivotVO vo;
        for (ContactFieldEntity e : contactFieldEntityList) {
            vo = new ContactFieldPivotVO();
            vo.setContactFieldId(e.getId());
            vo.setName(e.getLabel());
            vo.setType(Integer.valueOf(e.getType()));
            ContactFieldTypeEntity one = contactFieldTypeService.getOne(Wrappers.<ContactFieldTypeEntity>lambdaQuery().eq(ContactFieldTypeEntity::getId, e.getType()));
            vo.setTypeText(one.getCn());
            vo.setOptions(Arrays.asList(e.getOptions().split("，")));
            if (StringUtils.isNotBlank(e.getType()) && e.getType().equals("3")) {
                vo.setValue(new ArrayList<>());
            } else {
                vo.setValue("");
            }
            ContactFieldPivotEntity contactFieldPivotEntity = contactFieldPivotEntityMap.get(e.getId());
            if (contactFieldPivotEntity != null) {
                vo.setContactFieldPivotId(contactFieldPivotEntity.getId());
                String value = contactFieldPivotEntity.getValue();
                if (value != null){
                    if (value.startsWith("[")) {
                        vo.setValue(JSON.parseArray(value,String.class));
                    } else if (vo.getType().equals(3) && vo.getValue().equals("")){
                        //如果类型为3：多选，返回空集合
                        vo.setValue(Collections.EMPTY_LIST);
                    } else {
                        vo.setValue(value);
                    }
                }else {
                    vo.setValue(null);
                }
                if (TypeEnum.PICTURE.getCode().equals(e.getType())) {
                    vo.setPictureFlag(AliyunOssUtils.getUrl(contactFieldPivotEntity.getValue()));
                }
            }
            voList.add(vo);
        }
        return voList;
    }

    /**
     * @description 客户 - 客户详情 - 编辑用户画像
     * @author zhaojinjian
     * @createTime 2020/12/24 18:31
     */
    @Override
    public boolean updateContactFieldPivot(ContactFieldPivotDto param) {

        QueryWrapper<ContactFieldPivotEntity> contactFieldPivotWrapper = new QueryWrapper<>();
        contactFieldPivotWrapper.eq("contact_id", param.getContactId());
        List<ContactFieldPivotEntity> oldContactFieldPivotEntityList = this.list(contactFieldPivotWrapper);
        HashMap<Integer, String> contactFieldPivotEntityMap = new HashMap<>(oldContactFieldPivotEntityList.size());
        for (ContactFieldPivotEntity e : oldContactFieldPivotEntityList) {
            contactFieldPivotEntityMap.put(e.getContactFieldId(), e.getValue());
        }

        StringBuffer stringBuffer = new StringBuffer();
        List<Integer> contactFieldIdList = new ArrayList<>();
        List<ContactFieldPivotEntity> contactFieldPivotList = new ArrayList<>();
        List<ContactFieldPivotDto.UserPortrait> userPortraitList = JSON.parseArray(param.getUserPortrait(),ContactFieldPivotDto.UserPortrait.class);
        userPortraitList.forEach(item -> {
            if (item.getStatus() == 1){
                remove(Wrappers.<ContactFieldPivotEntity>lambdaQuery().eq(ContactFieldPivotEntity::getContactId,param.getContactId())
                        .eq(ContactFieldPivotEntity::getContactFieldId,item.getContactFieldId()));
                ContactFieldPivotEntity contactFieldPivotEntity = new ContactFieldPivotEntity();
                contactFieldPivotEntity.setId(item.getContactFieldPivotId());
                contactFieldPivotEntity.setContactFieldId(item.getContactFieldId());
                contactFieldPivotEntity.setContactId(param.getContactId());
                contactFieldPivotEntity.setValue(item.getValue());
                contactFieldPivotList.add(contactFieldPivotEntity);

                String oldValue = contactFieldPivotEntityMap.get(item.getContactFieldId());
                String newValue = item.getValue();
                String oldV = oldValue == null ? "" : oldValue;
                String newV = newValue == null ? "" : newValue;
                if (!oldV.equals(newV)) {
                    contactFieldIdList.add(item.getContactFieldId());
                }
            }
        });

//        List<ContactFieldEntity> contactFieldEntityList = contactFieldMapper.selectList(
//                new QueryWrapper<>(ContactFieldEntity.builder().status(1).build())
//        );
        List<ContactFieldEntity> contactFieldEntityList = contactFieldService.list(Wrappers.<ContactFieldEntity>lambdaQuery()
                .eq(ContactFieldEntity::getCorpId, CorpContextHolder.getCorpId())
                .eq(ContactFieldEntity::getStatus,1));
        HashMap<Integer, ContactFieldEntity> contactFieldEntityMap = new HashMap<>(contactFieldEntityList.size());
        for (ContactFieldEntity e : contactFieldEntityList) {
            contactFieldEntityMap.put(e.getId(), e);
        }

        for (Integer id : contactFieldIdList) {
            ContactFieldEntity contactFieldEntity = contactFieldEntityMap.get(id);
            stringBuffer.append(contactFieldEntity.getLabel()+" ");
        }
        boolean result = true ;
        if (!contactFieldPivotList.isEmpty()){
            result= this.saveOrUpdateBatch(contactFieldPivotList);

            if (result) {
                contactService.saveTrack(
                        param.getEmployeeId(),
                        param.getContactId(),
                        EventEnum.USER_PORTRAIT,
                        EventEnum.USER_PORTRAIT.getMsg() + ": " + stringBuffer.toString(),
                        1,
                        null);
            }
        }
        return result;
    }

    @Override
    public List labelList() {
        Integer corpId = CorpContextHolder.getCorpId();
        String s = WxApiUtils.requestGetAllTag(corpId);
        JSONArray array = JSON.parseArray(s);
        return array;
    }

    @Override
    public boolean labelPut(WorkContactTagDTO workContactTagDTO) {
      return contactTagService.labelPut(workContactTagDTO.getWxContactTagId(),workContactTagDTO.getName());
    }


    /**
     * @description 客户 - 客户详情 - 编辑用户画像
     * @author zhaojinjian
     * @createTime 2020/12/24 18:31
     */
    @Override
    public boolean updateContactFieldPivotWeChat(ContactFieldPivotDto param) {

        QueryWrapper<ContactFieldPivotEntity> contactFieldPivotWrapper = new QueryWrapper<>();
        contactFieldPivotWrapper.eq("contact_id", param.getContactId());
        List<ContactFieldPivotEntity> oldContactFieldPivotEntityList = this.list(contactFieldPivotWrapper);
        HashMap<Integer, String> contactFieldPivotEntityMap = new HashMap<>(oldContactFieldPivotEntityList.size());
        for (ContactFieldPivotEntity e : oldContactFieldPivotEntityList) {
            contactFieldPivotEntityMap.put(e.getContactFieldId(), e.getValue());
        }

        StringBuffer stringBuffer = new StringBuffer();
        List<Integer> contactFieldIdList = new ArrayList<>();
        List<ContactFieldPivotEntity> contactFieldPivotList = new ArrayList<>();
        List<ContactFieldPivotDto.UserPortrait> userPortraitList = JSON.parseArray(param.getUserPortrait(),ContactFieldPivotDto.UserPortrait.class);
        userPortraitList.forEach(item -> {
            if (item.getStatus() ==1){
                remove(Wrappers.<ContactFieldPivotEntity>lambdaQuery().eq(ContactFieldPivotEntity::getContactId,param.getContactId())
                        .eq(ContactFieldPivotEntity::getContactFieldId,item.getContactFieldPivotId()));
                ContactFieldPivotEntity contactFieldPivotEntity = new ContactFieldPivotEntity();
                contactFieldPivotEntity.setId(item.getContactFieldPivotId());
                contactFieldPivotEntity.setContactFieldId(item.getContactFieldId());
                contactFieldPivotEntity.setContactId(param.getContactId());
                contactFieldPivotEntity.setValue(item.getValue());
                contactFieldPivotList.add(contactFieldPivotEntity);

                String oldValue = contactFieldPivotEntityMap.get(item.getContactFieldId());
                String newValue = item.getValue();
                String oldV = oldValue == null ? "" : oldValue;
                String newV = newValue == null ? "" : newValue;
                if (!oldV.equals(newV)) {
                    contactFieldIdList.add(item.getContactFieldId());
                }
            }
        });

//        List<ContactFieldEntity> contactFieldEntityList = contactFieldMapper.selectList(
//                new QueryWrapper<>(ContactFieldEntity.builder().status(1).build())
//        );
        List<ContactFieldEntity> contactFieldEntityList = contactFieldService.list(Wrappers.<ContactFieldEntity>lambdaQuery()
                .eq(ContactFieldEntity::getCorpId, CorpContextHolder.getCorpId())
                .eq(ContactFieldEntity::getStatus,1));
        HashMap<Integer, ContactFieldEntity> contactFieldEntityMap = new HashMap<>(contactFieldEntityList.size());
        for (ContactFieldEntity e : contactFieldEntityList) {
            contactFieldEntityMap.put(e.getId(), e);
        }

        for (Integer id : contactFieldIdList) {
            ContactFieldEntity contactFieldEntity = contactFieldEntityMap.get(id);
            stringBuffer.append(contactFieldEntity.getLabel()+" ");
        }
        boolean result = true;
        if (!contactFieldPivotList.isEmpty()){
           result =this.saveOrUpdateBatch(contactFieldPivotList);
            if (result) {
                contactService.saveTrack(
                        param.getEmployeeId(),
                        param.getContactId(),
                        EventEnum.USER_PORTRAIT,
                        EventEnum.USER_PORTRAIT.getMsg() + ": " + stringBuffer.toString(),
                        2,
                        null);
            }

        }
        return result;
    }

    @Override
    public List<ContactFieldPivotVO> getCrmContactFieldPivotList(Integer contactId,Integer employeeId) {
        List<ContactFieldPivotVO> voList = new ArrayList<>();

//        WorkContactEmployeeEntity contactEmployeeEntity = workContactEmployeeService.getOne(new LambdaQueryWrapper<WorkContactEmployeeEntity>()
//                .eq(WorkContactEmployeeEntity::getCorpId, CorpContextHolder.getCorpId())
//                .eq(WorkContactEmployeeEntity::getContactId, contactId)
//                .eq(WorkContactEmployeeEntity::getEmployeeId, employeeId));
        WorkContactEmployeeEntity contactEmployeeEntity = workContactEmployeeService.getNewestRecordByContactIdAndEmployeeId(CorpContextHolder.getCorpId(), contactId, employeeId);
        if (JSONArray.parseArray(contactEmployeeEntity.getRemarkMobiles()).isEmpty()) {
            return voList;
        }

        CrmCustomQueryConditionDTO queryCondition = new CrmCustomQueryConditionDTO();
        queryCondition.setMobileTel(JSONArray.parseArray(contactEmployeeEntity.getRemarkMobiles()).get(0).toString());
        List<WorkCustomInfoEntity> workCustomInfoEntitys = workCustomInfoService.listByCondition(queryCondition);
        if (workCustomInfoEntitys.isEmpty()) {
            return voList;
        }
        WorkCustomInfoEntity workCustomInfoEntity = workCustomInfoEntitys.get(0);
        List<ContactFieldEntity> contactFieldEntityList = contactFieldService.list(Wrappers.<ContactFieldEntity>lambdaQuery()
                .eq(ContactFieldEntity::getCorpId, CorpContextHolder.getCorpId())
                .eq(ContactFieldEntity::getStatus,1));
        contactFieldEntityList.sort(Comparator.comparing(ContactFieldEntity::getOrder,Comparator.reverseOrder())
                .thenComparing(BaseEntity::getCreateTime,Comparator.reverseOrder()));

        //crm客户字典
        List<SysDictItem> crmDictList = remoteDictService.getCrmCustDict();
        ContactFieldPivotVO vo;
        for (ContactFieldEntity e : contactFieldEntityList) {
            vo = new ContactFieldPivotVO();
            vo.setContactFieldId(e.getId());
            vo.setName(e.getLabel());
            vo.setType(Integer.valueOf(e.getType()));
            ContactFieldTypeEntity one = contactFieldTypeService.getOne(Wrappers.<ContactFieldTypeEntity>lambdaQuery().eq(ContactFieldTypeEntity::getId, e.getType()));
            vo.setTypeText(one.getCn());
            vo.setOptions(Arrays.asList(e.getOptions().split("，")));
            switch (e.getName()) {
                case CrmFieldNameConstants.CUST_NO:
                    vo.setValue(workCustomInfoEntity.getCustNo());
                    break;
                case CrmFieldNameConstants.NAME:
                    vo.setValue(workCustomInfoEntity.getPecustName());
                    break;
                case CrmFieldNameConstants.SEX:
                    vo.setValue(valueToText(workCustomInfoEntity.getSex(),CrmDictTypeConstants.TYPE_SEX,crmDictList));
                    break;
                case CrmFieldNameConstants.AGE:
                    vo.setValue(workCustomInfoEntity.getAge());
                    break;
                case CrmFieldNameConstants.BIRTHDAY:
                    vo.setValue(workCustomInfoEntity.getBirthday());
                    break;
                case CrmFieldNameConstants.MOBILE:
                    vo.setValue(workCustomInfoEntity.getMobileTel());
                    break;
                case CrmFieldNameConstants.NATION:
                    vo.setValue(valueToText(workCustomInfoEntity.getNation(),CrmDictTypeConstants.TYPE_NATION,crmDictList));
                    break;
                case CrmFieldNameConstants.HIGHEST_EDU:
                    vo.setValue(valueToText(workCustomInfoEntity.getHighestEdu(),CrmDictTypeConstants.TYPE_HIGHEST_EDU,crmDictList));
                    break;
                case CrmFieldNameConstants.PROFESSION:
                    vo.setValue(valueToText(workCustomInfoEntity.getProfession(),CrmDictTypeConstants.TYPE_PROFESSION,crmDictList));
                    break;
                case CrmFieldNameConstants.ADDRESS:
                    vo.setValue(workCustomInfoEntity.getContactAddr());
                    break;
                case CrmFieldNameConstants.CERT_TYPE:
                    vo.setValue(valueToText(workCustomInfoEntity.getCertType(),CrmDictTypeConstants.TYPE_CERT_TYPE,crmDictList));
                    break;
                case CrmFieldNameConstants.CERT_NO:
                    vo.setValue(workCustomInfoEntity.getCertNo());
                    break;
                case CrmFieldNameConstants.CERT_VALID_DATE:
                    vo.setValue(workCustomInfoEntity.getCertValidDate());
                    break;
                case CrmFieldNameConstants.OPEN_DATE:
                    vo.setValue(workCustomInfoEntity.getOpenDate());
                    break;
                case CrmFieldNameConstants.ASSETS_LEVEL:
                    vo.setValue(valueToText(workCustomInfoEntity.getAssetsLevel(),CrmDictTypeConstants.TYPE_ASSETS_LEVEL,crmDictList));
                    break;
                case CrmFieldNameConstants.SPECIAL_LEVEL:
                    vo.setValue(valueToText(workCustomInfoEntity.getSpecialLevel(),CrmDictTypeConstants.TYPE_ASSETS_LEVEL,crmDictList));
                    break;
                case CrmFieldNameConstants.RISK_LEVEL:
                    vo.setValue(valueToText(workCustomInfoEntity.getRiskLevel(),CrmDictTypeConstants.TYPE_RISK_LEVEL,crmDictList));
                    break;
                case CrmFieldNameConstants.CUST_MGR_NAME:
                    vo.setValue(workCustomInfoEntity.getCustMgr());
                    break;
            }
            voList.add(vo);
        }
        return voList;
    }

    /**
     * CRM客户字典值转为文本
     * @param dictValue 字典值
     * @param dictType  字典类型
     * @param crmDictList 字典数据集合
     * @return 如果码值有对应文本则返回文本，没有则返回原来的码值
     */
    private String valueToText(String dictValue, String dictType, List<SysDictItem> crmDictList) {
        List<String> textList = crmDictList.stream()
                .filter(l -> l.getType().equals(dictType) && l.getValue().equals(dictValue))
                .map(l->l.getLabel())
                .collect(Collectors.toList());
        if (textList.isEmpty()) {
            return dictValue;
        } else {
            return textList.get(0);
        }
    }

}
